import React, { useState, useRef } from "react";
import {
  Box,
  Flex,
  Radio,
  RadioGroup,
  NumberInput,
  NumberInputField,
  Button,
  Modal,
  ModalOverlay,
  ModalContent,
  ModalHeader,
  ModalFooter,
  ModalBody,
  ModalCloseButton,
  Input,
  useToast,
  Text,
  VStack,
} from "@chakra-ui/react";
import { DPIGroup, DpiConfig } from "@/src/types/types.d";
import { useTranslation } from "@/src/i18n";
import { HexColorPicker } from "react-colorful";

interface DpiInputGroupProps {
  dpiGroups: DPIGroup[];
  selectedDpi: number;
  curDpiEditValue: number;
  dpiConfig: DpiConfig;
  onRadioChange: (value: string) => void;
  onInputValueChanging: (value: number, index: number) => void;
  onEditDpiData?: (
    dpiValue: number,
    dpiColor: string,
    dpiIndex: number
  ) => Promise<void>;
}

const DpiInputGroup: React.FC<DpiInputGroupProps> = ({
  dpiGroups,
  selectedDpi,
  curDpiEditValue,
  dpiConfig,
  onRadioChange,
  onInputValueChanging,
  onEditDpiData,
}) => {
  const { t } = useTranslation("");
  const toast = useToast();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [dpiValue, setDpiValue] = useState("");
  const [selectedColor, setSelectedColor] = useState("#2dcb7f");
  const [isAddDpi, setIsAddDpi] = useState(false);
  const [dpiIndex, setDpiIndex] = useState(-1);

  // 引用主界面中当前选中的DPI输入框
  const mainInputRef = useRef<HTMLInputElement>(null);

  // 生成背景颜色（主色 + 1a透明度）
  const generateBgColor = (color: string): string => {
    return color + "1a";
  };

  // 处理自定义颜色变化
  const handleColorChange = (color: string) => {
    setSelectedColor(color);
  };

  const handleOpenModal = () => {
    setIsAddDpi(true);
    setDpiValue("");
    setSelectedColor("#2dcb7f");
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
  };

  const handleEditDpiData = (dpiInfo: DPIGroup) => {
    setIsAddDpi(false);
    setIsModalOpen(true);
    setSelectedColor(dpiInfo.dpiColor);
    setDpiValue(dpiInfo.dpiValue.toString());
    setDpiIndex(dpiInfo.dpiIndex);
  };

  const handleConfirm = async () => {
    const minValue = dpiConfig.min;

    if (!dpiValue || Number(dpiValue) < minValue) {
      toast({
        title: t("dpiErrorTip"),
        status: "warning",
        duration: 3000,
        isClosable: true,
        position: "top",
      });
      return;
    }

    try {
      const newDpiColor = selectedColor;

      if (onEditDpiData && !isAddDpi) {
        await onEditDpiData(Number(dpiValue), newDpiColor, dpiIndex);
      }

      setIsModalOpen(false);
    } catch (error) {
      console.error("修改第" + dpiIndex + "个DPI档位失败:", error);
    }
  };

  const changeDpiValue = (value: number) => {
    let inputVal = value;

    if (isNaN(inputVal)) {
      inputVal = 0;
    }

    inputVal = Math.max(0, Math.min(inputVal, 24000));

    setDpiValue(inputVal.toString());
  };

  if (!dpiGroups || dpiGroups.length === 0) {
    return <Box>No DPI groups available.</Box>;
  }

  return (
    <>
      <RadioGroup
        onChange={onRadioChange}
        value={selectedDpi.toString()}
        className="flex gap-[16px]"
      >
        {dpiGroups.map((dpiInfo, index) => (
          <Flex
            direction="column"
            alignItems="center"
            gap={2}
            key={dpiInfo.key}
          >
            <Radio value={index.toString()} color={dpiInfo.dpiColor}>
              {selectedDpi === index ? (
                <Box
                  color={dpiInfo.dpiColor}
                  fontSize="16px"
                  fontWeight="500"
                  height="20px"
                >
                  {t("currentDpi")}
                </Box>
              ) : (
                <Box
                  fontSize="14px"
                  color={dpiInfo.dpiColor}
                  fontWeight="400"
                  height="20px"
                ></Box>
              )}
            </Radio>
            <Box
              width="112px"
              height="50px"
              p={2}
              mb={4}
              border={
                selectedDpi.toString() === dpiInfo.key ? "1px solid" : "none"
              }
              borderColor={dpiInfo.dpiColor}
              bg={dpiInfo.dpiBgColor}
              borderRadius="md"
              display="flex"
              justifyContent="center"
              alignItems="center"
            >
              <NumberInput
                value={
                  selectedDpi.toString() === dpiInfo.key
                    ? curDpiEditValue
                    : dpiInfo.dpiValue
                }
                onChange={(_, value) => onInputValueChanging(value, index)}
                onKeyUp={(e) => {
                  if (e.key === "Enter") {
                    // onInputValueChange(curDpiEditValue);
                  }
                }}
                onClick={() => {
                  if (selectedDpi.toString() === dpiInfo.key) {
                    handleEditDpiData(dpiInfo);
                  }
                }}
                min={dpiConfig?.min || 200}
                max={dpiConfig?.max || 12000}
                size="xl"
                isReadOnly={selectedDpi.toString() !== dpiInfo.key}
              >
                <NumberInputField
                  ref={
                    selectedDpi.toString() === dpiInfo.key
                      ? mainInputRef
                      : undefined
                  }
                  border="none"
                  fontWeight={
                    selectedDpi.toString() === dpiInfo.key ? "bold" : "normal"
                  }
                  textAlign="center"
                  color={dpiInfo.dpiColor}
                  _focus={{
                    borderColor: "transparent",
                    boxShadow: "none",
                  }}
                />
              </NumberInput>
            </Box>
          </Flex>
        ))}
      </RadioGroup>

      {/* 弹窗组件 */}
      <Modal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        onCloseComplete={() => {
          setTimeout(() => {
            if (mainInputRef.current) {
              mainInputRef.current.blur();
            }
          }, 100);
        }}
        isCentered
      >
        <ModalOverlay />
        <ModalContent>
          <ModalHeader>{t("addDpiTitle")}</ModalHeader>
          <ModalCloseButton />
          <ModalBody>
            <VStack spacing={4} align="stretch">
              {/* DPI数值输入 */}
              <Input
                value={dpiValue}
                onChange={(evt) => changeDpiValue(parseInt(evt.target.value))}
                placeholder={t("dpiPlaceholder")}
                minLength={1}
                maxLength={20}
              />

              {/* 颜色选择区域 */}
              <Box>
                <Text mb={2} fontSize="sm" fontWeight="medium">
                  {t("customColor")}
                </Text>
                {/* 自定义颜色拾取器 */}
                <Box
                  p={4}
                  border="1px solid #e2e8f0"
                  borderRadius="md"
                  bg="gray.50"
                >
                  <HexColorPicker
                    color={selectedColor}
                    onChange={handleColorChange}
                  />
                  <Flex
                    bg="#2D3748"
                    mt={3}
                    p={3}
                    className="items-center"
                    rounded={6}
                  >
                    <Text fontSize="sm">{t("hexValue")}</Text>
                    <Input
                      size="sm"
                      value={selectedColor}
                      onChange={(e) => handleColorChange(e.target.value)}
                      placeholder="#000000"
                      maxW="100px"
                    />
                  </Flex>
                </Box>

                {/* 颜色预览 */}
                <Box mt={4}>
                  <Text mb={2} fontSize="sm" fontWeight="medium">
                    {t("colorPreview")}
                  </Text>
                  <Box
                    w="112px"
                    h="50px"
                    p={2}
                    border="1px solid"
                    borderColor={selectedColor}
                    bg={generateBgColor(selectedColor)}
                    borderRadius="md"
                    display="flex"
                    justifyContent="center"
                    alignItems="center"
                  >
                    <Text
                      fontSize="14px"
                      fontWeight="bold"
                      color={selectedColor}
                      textAlign="center"
                    >
                      {dpiValue || "DPI"}
                    </Text>
                  </Box>
                </Box>
              </Box>
            </VStack>
          </ModalBody>
          <ModalFooter>
            <Button variant="ghost" mr={3} onClick={handleCloseModal}>
              {t("cancel")}
            </Button>
            <Button
              className="primary-btn !min-w-[60px] !h-10 !font-family-msyh !text-[14px] !rounded-[8px]"
              colorScheme="blue"
              onClick={handleConfirm}
            >
              {t("confirm")}
            </Button>
          </ModalFooter>
        </ModalContent>
      </Modal>
    </>
  );
};

export default DpiInputGroup;
